package com.cjr.rabbitmq;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cjr.pojo.SeckillMessage;
import com.cjr.pojo.SeckillOrder;
import com.cjr.pojo.User;
import com.cjr.service.IGoodsService;
import com.cjr.service.IOrderService;
import com.cjr.utils.JsonUtil;
import com.cjr.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author cjr
 * @description RabbitMQ receiver
 */
@Service
@Slf4j
public class MQReceiver {

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private IOrderService orderService;


    @RabbitListener(queues = "seckillQueue")
    public void receive(String msg) {
        log.info("QUEUE接受消息：" + msg);
        SeckillMessage message = JsonUtil.jsonStr2Object(msg, SeckillMessage.class);
        Long goodsId = message.getGoodsId();
        User user = message.getUser();
        GoodsVo goods = goodsService.findGoodsVoByGoodsId(goodsId);
        if (goods.getStockCount() < 1) {
            return;
        }
        // determine whether buy more than once
        String seckillOrderJson = (String) redisTemplate.opsForValue().get(
                "order:" + user.getId() + ":" + goodsId);
        if (StringUtils.hasLength(seckillOrderJson)) {
            return;
        }
        orderService.seckill(user, goods);
    }
}
